package com.fx.zuul.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * des:
 *
 * @author fxiao
 * @date 2020/12/18 19:15
 */
@Component
public class WebFilter extends ZuulFilter {
    private final Logger log= LoggerFactory.getLogger(this.getClass());
    /**
     * 设置为前置过滤器
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 设置过滤器等级，数字越小越先使用
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 开启这个过滤器
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 这里写自己的业务逻辑<br>
     * 从这里面可以拿到请求头,然后设置之后就可以让被代理的接口拿到
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("fxout:123456");
        //得到上下文
        RequestContext currentContext=RequestContext.getCurrentContext();
        //得到request域
        HttpServletRequest request=currentContext.getRequest();
        //zuul自带的进行请求转发的那个方法就跳过
        if ("OPTIONS".equals(request.getMethod())){
            return null;
        }
        //得到请求头里面的这个值
        String header=request.getHeader("Authorization");
        log.debug("过滤器的header -------> " + header);
        if (!StringUtils.isEmpty(header)) {
            //把信息传递下去
            currentContext.addZuulRequestHeader("Authorization",header);
            System.out.println("currentContext -------> " + currentContext);
            log.debug("currentContext -------> " + currentContext);
        }
        return currentContext;
    }
}
